#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
页面导航控制器
管理界面状态和导航逻辑
"""

from typing import Dict, Any, Optional
import logging

logger = logging.getLogger(__name__)

class PageStateMachine:
    """
    页面状态机，负责识别当前页面和控制页面导航
    """
    
    # 页面类型枚举
    PAGE_TYPES = {
        "LOGIN_PAGE": "登录页",
        "COURSE_LIST": "评教列表页",
        "CHOICE_QUESTION": "选择题页",
        "TEXT_QUESTION": "填空题页",
        "COMPLETION": "完成页",
        "ERROR": "错误页面"
    }
    
    def __init__(self):
        """初始化页面状态机"""
        self.current_page = None
        self.browser = None  # 实际项目中需要传入浏览器控制实例
        self.xpath_patterns = {
            self.PAGE_TYPES["COURSE_LIST"]: "//div[contains(@class, 'course-list')]",
            self.PAGE_TYPES["CHOICE_QUESTION"]: "//div[contains(@class, 'choice-question')]",
            self.PAGE_TYPES["TEXT_QUESTION"]: "//div[contains(@class, 'text-question')]",
            self.PAGE_TYPES["COMPLETION"]: "//div[contains(@class, 'completion-notice')]"
        }
    
    def set_browser(self, browser):
        """设置浏览器实例"""
        self.browser = browser
    
    def detect_current_page(self) -> str:
        """
        通过XPath识别当前所处界面类型
        
        Returns:
            str: 界面类型枚举（评教列表页/选择题页/填空题页/完成页）
        """
        if not self.browser:
            logger.error("浏览器实例未初始化")
            return self.PAGE_TYPES["ERROR"]
        
        try:
            # 尝试匹配各类页面的特征元素
            for page_type, xpath in self.xpath_patterns.items():
                try:
                    # 检查是否存在特定元素，判断页面类型
                    element = self.browser.find_element_by_xpath(xpath)
                    if element:
                        self.current_page = page_type
                        return page_type
                except:
                    # 元素不存在，继续检查下一个页面类型
                    continue
            
            # 未识别到任何已知页面
            logger.warning("当前页面类型无法识别")
            return self.PAGE_TYPES["ERROR"]
            
        except Exception as e:
            logger.error(f"页面识别过程发生异常: {e}")
            return self.PAGE_TYPES["ERROR"]
    
    def navigate_to_next(self, current_page: str, status_code: int = 0) -> bool:
        """
        根据状态机规则触发点击事件，控制页面导航
        
        Args:
            current_page: 当前界面类型
            status_code: 操作结果状态码
            
        Returns:
            bool: 导航操作是否成功
        """
        logger.info(f"正在从 {current_page} 导航至下一页面")
        
        try:
            if current_page == self.PAGE_TYPES["COURSE_LIST"]:
                # 在课程列表页选择第一个待评价课程
                xpath = "//div[contains(@class, 'course-item')][1]//button[contains(@class, 'evaluate')]"
                self._click_element(xpath)
                return True
                
            elif current_page == self.PAGE_TYPES["CHOICE_QUESTION"]:
                # 选择题页面完成后应自动跳转，如果没有则点击下一步
                xpath = "//button[contains(@class, 'next-step')]"
                self._click_element(xpath)
                return True
                
            elif current_page == self.PAGE_TYPES["TEXT_QUESTION"]:
                # 填空题页面完成后点击提交
                xpath = "//button[contains(@class, 'submit')]"
                self._click_element(xpath)
                return True
                
            elif current_page == self.PAGE_TYPES["COMPLETION"]:
                # 评价完成页面点击返回
                xpath = "//button[contains(@class, 'back-to-list')]"
                self._click_element(xpath)
                return True
                
            else:
                logger.warning(f"未知页面类型: {current_page}, 无法执行导航")
                return False
                
        except Exception as e:
            logger.error(f"导航过程发生异常: {e}")
            return False
    
    def _click_element(self, xpath: str) -> bool:
        """
        点击指定XPath的元素
        
        Args:
            xpath: 元素的XPath表达式
            
        Returns:
            bool: 点击操作是否成功
        """
        try:
            element = self.browser.find_element_by_xpath(xpath)
            element.click()
            logger.info(f"成功点击元素: {xpath}")
            return True
        except Exception as e:
            logger.error(f"点击元素失败: {xpath}, 错误: {e}")
            return False 